import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { routerRedux } from 'dva/router';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Input, Button, Select, Modal, message, Tabs } from 'antd';
import Editor from '@/utils/Editor';
import styles from "./index.less";

const FormItem = Form.Item;
const Option = Select.Option;
const TabPane = Tabs.TabPane;
const { TextArea } = Input;
@connect(({ process, loading }) => ({
  process,
  loading: loading.effects['antistopReply/fetch'],
}))


class AddText extends Component {
  state = {
    list: [],
    total: '',
    showModelA: false,
    showButton: true,
    dataSource: [],
    name: '',
    content: '',
    dictId: null,
  };

  componentDidMount() {
    this.list()
  }

  list = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'antistopReply/fetche',
        payload: { robotId: currentUser.robotId },
        callback: res => {
          console.log('列表数据', res);
          let temp = res
          // temp.map((item, index) => item['key'] = index)
          this.setState({
            dataSource: temp,
          })
        },
      });
    });
  }

  addapi = (val) => { // fetchc'
    const { dictId } = this.state
    if (dictId) {
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'antistopReply/fetchc',
          payload: { dictId: this.state.dictId, answer: val },
          callback: res => {
            console.log('列表数据', res);
            if (res.status) {
              message['success'](`${res.msg}`)
              setTimeout(() => {
                dispatch(routerRedux.push({
                  pathname: '/knowledge/antistopReply',
                }));
              }, 1000)
            }
          },
        });
      });
    } else {
      message['error']('实体名称不能为空')
    }

  }


  handleDeletes = () => {
    console.log('新增')
    this.list()
    this.setState({ showModelA: true })
  }

  handleChange = (value, ) => {
    console.log(value);
    this.setState({
      dictId: value[0],
      name: value[1]
    })
  }

  knowBase = () => {
    const { dispatch } = this.props;
    if (this.state.dictId === null) {
      message.error('请选择一项')
    } else {
      dispatch({
        type: 'antistopReply/fetchf',
        payload: { dictId: this.state.dictId },
        callback: res => {
          console.log('词典认证', res);
          if (!res.enable) {
            this.setState({ showModelA: false, showButton: false })
            message['success']('实体认证成功')
          } else {
            message['error']('该实体已被使用，请选择其它实体！')
            this.setState({
              dictId: '',
              name: ''
            })
          }
        },
      });
    }
  }

  jumpDictionaryPage = () => {

    const w = window.open('about:blank');
    w.location.href = '/basic/customDictionary'
    this.setState({ showModelA: false })
  }

  // eslint-disable-next-line react/sort-comp
  save() {
    console.log(this.ueditor.getUeditorContent())
    this.addapi(this.ueditor.getUeditorContent())

  }

  saveTextArea = () => {
    console.log('保存文本')
    const { value } = this.state
    this.addapi(value)
  }

  textAreaid = e => {
    // console.log(e.target.value) 
    this.setState({ value: e.target.value })
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        xs: 24,
        sm: 4,
        md: 3
      },
      wrapperCol: {
        xs: 24,
        sm: 20,
        md: 10
      }
    }
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div className={styles.backgroundp}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10,color: '#4B5475', fontWeight: 600  }} xs={24}>
                <div className={styles.title}>
                  <span>新增关键词回复</span>
                </div>
              </Col>
            </Row>
            <Card
              style={{ zIndex: 1 }}
              bordered={false}
            >
              <Form layout="horizontal">
                <FormItem label='关键词实体' {...FormItemLayont}>
                  {this.state.showButton === true ? <div className={styles.buttong2} onClick={this.handleDeletes}><span> <Icon type="plus" style={{ marginRight: 5 }} /></span><span><FormattedMessage id="app.antistopReply.add" /></span></div> : ''}
                  {this.state.showButton === true ? '' : <div><span className={styles.configuration}>{this.state.name}</span> <span className={styles.buttong2} onClick={this.handleDeletes}><span> <Icon type="edit" style={{ marginRight: 5 }} /></span><span><FormattedMessage id="app.antistopReply.change" /></span></span></div>}
                </FormItem>
                <FormItem label='关键词回复' {...FormItemLayont}>
                  <Tabs defaultActiveKey="1" style={{ width: 650 }}>
                    <TabPane tab="编辑富文本" key="1">
                      <div className='fuwenben' style={{ lineHeight: '20px', width: 640, zIndex: 1 }}>
                        <Editor content={this.state.content} name="content" id="content" height="300" width="500" ref={r => this.ueditor = r} />
                        <div className='zdyButtonA'>
                          <Button type="primary" htmlType='button' style={{ marginTop: 10 }} onClick={() => this.save()}>保存</Button>
                        </div>

                      </div>
                    </TabPane>
                    <TabPane tab="编辑文本" key="2">
                      <TextArea rows={4} style={{ height: 320 }} onChange={this.textAreaid} />
                      <div className='zdyButtonA'>
                        <Button type="primary" htmlType='button' style={{ marginTop: 10 }} onClick={() => this.saveTextArea()}>保存</Button>
                      </div>
                    </TabPane>
                  </Tabs>

                </FormItem>
              </Form>
            </Card>

            <Modal
              // style={{zIndex:99999999}}
              className='modelZdy'
              width={490}
              footer={null}
              title='添加/更换实体'
              visible={this.state.showModelA}
              okText={<FormattedMessage id="app.customDictionary.save" />}
              cancelText={<FormattedMessage id="app.customDictionary.cancel" />}
              onCancel={() => {
                this.setState({ showModelA: false })
              }}
              onOk={this.businessWayA}// 确定方法开出去
            >
              <Form layout="inline">
                <FormItem onSubmit={this.coreWordOne} >
                  <Select showSearch={true} placeholder="请选择" style={{ width: 220 }} onChange={this.handleChange}>
                    {
                      this.state.dataSource.map((item, index) => {
                        return (
                          <Option value={[item._id, item.name]}>{item.name}</Option>
                        )
                      })
                    }
                  </Select>
                </FormItem>
                <FormItem   >
                  <Button onClick={this.knowBase}>选择</Button>
                </FormItem>
                <FormItem   >
                  <Button type='primary' onClick={this.jumpDictionaryPage}>添加实体</Button>
                </FormItem>
              </Form>
              <div style={{ height: 20 }}></div>
            </Modal>
          </div>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}


export default connect(({ user }) => ({ // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(AddText));
